var express = require('express');
var { User } = require('../sql/user_mysql');
var generatorToken = require('../utils/generatorToken');
const router = express.Router();
var decrypt = require('../utils/decrypt');

router.post('/register', async (req, res) => {
	let usernameReg = /^[a-zA-Z0-9]{0,16}$/;
	let passwordReg = /^[a-zA-Z0-9_\.]{8,16}$/;
	let { username, password } = req.body;
	// let { username: unUsername, password: unPassword } = req.body;
	// let username = decrypt(unUsername);
	// let password = decrypt(unPassword);
	if (!usernameReg.test(username)) {
		res.send({
			message: '用户名只能0-16位字母+数字组合',
			status: false,
			success: false,
		});
		return;
	}
	if (!passwordReg.test(password)) {
		res.send({
			message: '密码只能8-16位大小写字母+数字+.组合',
			status: false,
			success: false,
		});
		return;
	}
	let findUser = await User.findOne({ where: { username } });
	if (findUser) {
		res.send({
			message: '该用户名已注册！',
			status: false,
			success: false,
		});
		return;
	}
	User.create(req.body)
		.then((user) => {
			res.send({
				message: `注册成功！用户名为 ${user.username}`,
				status: true,
				success: true,
			});
		})
		.catch((err) => {
			res.send({
				message: err,
				status: false,
				success: false,
			});
		});
});

router.post('/login', async (req, res) => {
	let { username: unUsername, password: unPassword } = req.body;
	let username = decrypt(unUsername);
	let password = decrypt(unPassword);
	let findUser = await User.findOne({ where: { username } });
	if (!findUser) {
		res.send({
			status: false,
			success: false,
			message: '用户名不存在！',
		});
		return;
	}
	let checkPassword = await User.findOne({ where: { username, password } });
	if (!checkPassword) {
		res.send({
			status: false,
			success: false,
			message: '密码不正确，请重新输入！',
		});
		return;
	}
	let token = generatorToken(username);
	User.update({ token }, { where: { username } });
	res.send({
		status: true,
		success: true,
		token,
		message: '登录成功！',
	});
});

router.get('/userList', async (req, res) => {
	let data = await User.findAll();
	res.send({
		message: '查询成功',
		data: data.map((item) => ({
			username: item.username,
		})),
	});
});

module.exports = router;
